package com.amumu.drama.common.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日期工具类
 * Created by macro on 2019/1/29.
 */
public class DateUtils {

    /**
     * 从Date类型的时间中提取日期部分
     */
    public static Date getDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 从Date类型的时间中提取时间部分
     */
    public static Date getTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.YEAR, 1970);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    //判断时间戳是否属于某个时间段
    public static boolean timestampInTime(String startTime, String endTime, DateTime nowTime) {
        if ((StrUtil.isBlank(startTime) && StrUtil.isBlank(endTime)) || nowTime == null) {
            return false;
        }

        if (StringUtils.isNotBlank(startTime)) {
            LocalTime startLocalTime = getTimeByString(startTime);
            //比较LocalTime的大小
            if (startLocalTime.isAfter(LocalTime.of(nowTime.hour(true), nowTime.minute(), nowTime.second()))) {
                return false;
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            LocalTime endLocalTime = getTimeByString(endTime);
            //比较LocalTime的大小
            if (endLocalTime.isBefore(LocalTime.of(nowTime.hour(true), nowTime.minute(), nowTime.second()))) {
                return false;
            }
        }
        return true;
    }

    private static LocalTime getTimeByString(String startTime) {
        List<String> split = StrUtil.split(startTime, ":");
        Integer hour = 0;
        Integer minute = 0;
        Integer second = 0;
        for (int i = 0; i < split.size(); i++) {
            if (i == 0) {
                hour = Integer.parseInt(split.get(i));
            } else if (i == 1) {
                minute = Integer.parseInt(split.get(i));
            } else if (i == 2) {
                second = Integer.parseInt(split.get(i));
            } else {
                break;
            }
        }
        return LocalTime.of(hour, minute, second);
    }
}
